<?php
namespace Opencart\Admin\Controller\Catalog;
class ProductImportExport extends \Opencart\System\Engine\Controller {
    public function index(): void {
        $this->load->language('catalog/product_import_export');

        $this->document->setTitle($this->language->get('heading_title'));

        $data['breadcrumbs'] = [];

        $data['breadcrumbs'][] = [
            'text' => $this->language->get('text_home'),
            'href' => $this->url->link('common/dashboard', 'user_token=' . $this->session->data['user_token'])
        ];

        $data['breadcrumbs'][] = [
            'text' => $this->language->get('heading_title'),
            'href' => $this->url->link('catalog/product_import_export', 'user_token=' . $this->session->data['user_token'])
        ];

        $data['export'] = $this->url->link('catalog/product_import_export|export', 'user_token=' . $this->session->data['user_token'], true);
        $data['user_token'] = $this->session->data['user_token'];

        if (isset($this->session->data['error_warning'])) {
            $data['error_warning'] = $this->session->data['error_warning'];
            unset($this->session->data['error_warning']);
        } else {
            $data['error_warning'] = '';
        }

        if (isset($this->session->data['success'])) {
            $data['success'] = $this->session->data['success'];
            unset($this->session->data['success']);
        } else {
            $data['success'] = '';
        }

        $data['header'] = $this->load->controller('common/header');
        $data['column_left'] = $this->load->controller('common/column_left');
        $data['footer'] = $this->load->controller('common/footer');

        $this->response->setOutput($this->load->view('catalog/product_import_export', $data));
    }

    public function export(): void {
        $this->load->language('catalog/product_import_export');

        // 验证用户token
        if (!isset($this->session->data['user_token']) || !isset($this->request->get['user_token']) || ($this->session->data['user_token'] != $this->request->get['user_token'])) {
            $this->response->redirect($this->url->link('common/login', '', true));
            return;
        }

        // 验证权限
        // if (!$this->user->hasPermission('modify', 'catalog/product_import_export')) {
        //     $this->session->data['error_warning'] = $this->language->get('error_permission');
        //     $this->response->redirect($this->url->link('catalog/product_import_export', 'user_token=' . $this->session->data['user_token']));
        //     return;
        // }

        $this->load->model('catalog/product');
        
        $products = $this->model_catalog_product->getProducts();

        // CSV Header
        $csv_header = [
            'product_id',
            'name',
            'description_1',  // 第一部分描述
            'description_2',  // 第二部分描述
            'description_3',  // 第三部分描述
            'meta_title',
            'meta_description',
            'meta_keyword',
            'attributes', 
            'options', 
        ];

        $output = fopen('php://output', 'w');
        
        // Set headers for download
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename=products_' . date('Y-m-d_His') . '.csv');
        
        // Add BOM for UTF-8
        fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));
        
        // Write header
        fputcsv($output, $csv_header);

        // Write products
        foreach ($products as $product) {
            // 获取产品属性，包含attribute_description的name
            $product_attributes = $this->db->query("SELECT pa.attribute_id, pa.text, pa.language_id, ad.name as attribute_name 
                FROM " . DB_PREFIX . "product_attribute pa
                LEFT JOIN " . DB_PREFIX . "attribute_description ad ON (pa.attribute_id = ad.attribute_id)
                WHERE pa.product_id = '" . (int)$product['product_id'] . "' 
                AND pa.language_id = '" . (int)$this->config->get('config_language_id') . "'
                AND ad.language_id = '" . (int)$this->config->get('config_language_id') . "'")->rows;
            
            // 格式化属性
            $attributes = [];
            foreach ($product_attributes as $attribute) {
                $attributes[] = [
                    'attribute_id' => (string)$attribute['attribute_id'],  // 确保是字符串格式
                    'text' => $attribute['text'],
                    'name' => $attribute['attribute_name'],
                    'language_id' => (int)$attribute['language_id']
                ];
            }
            $attributes_str = json_encode($attributes, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
            
            // 获取产品的options
            $product_options = $this->db->query("SELECT 
                po.option_id,
                o.type,
                po.product_option_id,
                pov.option_value_id,
                ovd.name
                FROM " . DB_PREFIX . "product_option po 
                LEFT JOIN `" . DB_PREFIX . "option` o ON (po.option_id = o.option_id) 
                LEFT JOIN " . DB_PREFIX . "product_option_value pov ON (po.product_option_id = pov.product_option_id)
                LEFT JOIN " . DB_PREFIX . "option_value ov ON (pov.option_value_id = ov.option_value_id)
                LEFT JOIN " . DB_PREFIX . "option_value_description ovd ON (ov.option_value_id = ovd.option_value_id 
                    AND ovd.language_id = '" . (int)$this->config->get('config_language_id') . "')
                WHERE po.product_id = '" . (int)$product['product_id'] . "'")->rows;

            // 重新组织options数据
            $options = array();
            foreach ($product_options as $option) {
                if (!isset($options[$option['option_id']])) {
                    $options[$option['option_id']] = array(
                        'option_id' => $option['option_id'],
                        'type' => $option['type'],
                        'values' => array()
                    );
                }
                if (!empty($option['name'])) {
                    $options[$option['option_id']]['values'][] = array(
                        'option_value_id' => $option['option_value_id'],
                        'name' => $option['name']
                    );
                }
            }
            
            $product['options'] = !empty($options) ? json_encode(array_values($options), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) : '';
            
            // 只删除特定的图片标签
            $clean_description = str_replace('<img src="https://nailbulk.local/image/catalog/product/2024/11/19/7502/7542024727_41605144.jpg" alt="undefined" width="5" height="5"/>', '', $product['description']);
            $clean_description = str_replace('<img src="https://nailbulk.local/image/catalog/product/2024/11/19/2491/1424784049_41605144.jpg" height="3">', '', $clean_description);
            $clean_description = str_replace('<img src="https://nailbulk.local/image/catalog/product/2024/11/19/2908/3111504691_41605144.jpg" height="3"/>', '', $clean_description);
            $clean_description = str_replace('<img src="https://nailbulk.local/image/catalog/product/2024/11/19/3709/1425939835_41605144.jpg" height="1">', '', $clean_description);
            $clean_description = str_replace('<img src="https://nailbulk.local/image/catalog/product/2024/11/19/9262/O1CN01SGyv8b2C1fRMr8aNR_!!1838578414-0-cib.jpg" alt="undefined" width="5" height="5 "/>', '', $clean_description);
            $clean_description = str_replace('【', '[', $clean_description);
            $clean_description = str_replace('】', ']', $clean_description);
            $clean_description = str_replace('（', '(', $clean_description);
            $clean_description = str_replace('）', ')', $clean_description);
            $clean_description = str_replace('.................................................................', '', $clean_description);
            
            // 将描述分割成多个部分，每部分最大30000字符
            $max_length = 30000;
            $description_parts = [];
            $remaining = $clean_description;
            
            // 分割描述成最多3个部分
            for ($i = 0; $i < 3; $i++) {
                if (empty($remaining)) {
                    $description_parts[] = '';
                    continue;
                }
                
                if (strlen($remaining) > $max_length) {
                    // 在空格或标点处分割，避免单词被截断
                    $part = mb_substr($remaining, 0, $max_length, 'UTF-8');
                    $last_space = max(
                        strrpos($part, ' '),
                        strrpos($part, '.'),
                        strrpos($part, '。'),
                        strrpos($part, '！'),
                        strrpos($part, '?'),
                        strrpos($part, '？')
                    );
                    
                    if ($last_space !== false) {
                        $part = mb_substr($remaining, 0, $last_space + 1, 'UTF-8');
                    }
                    
                    $description_parts[] = $part;
                    $remaining = mb_substr($remaining, strlen($part), null, 'UTF-8');
                } else {
                    $description_parts[] = $remaining;
                    $remaining = '';
                }
            }
            
            // 如果还有剩余内容，添加到最后一部分
            if (!empty($remaining)) {
                $description_parts[2] .= '...(content truncated)';
            }
            
            // 确保有3个部分，不足的补空字符串
            while (count($description_parts) < 3) {
                $description_parts[] = '';
            }
            
            $row = [
                $product['product_id'],
                $product['name'],
                $description_parts[0],  // 描述第一部分
                $description_parts[1],  // 描述第二部分
                $description_parts[2],  // 描述第三部分
                $product['meta_title'],
                $product['meta_description'],
                $product['meta_keyword'],
                $attributes_str,
                $product['options'],
                
            ];
            fputcsv($output, $row);
        }

        fclose($output);
        exit();
    }

    protected function editProduct($product_id, $data) {
        // Update product description
        foreach ($data['product_description'] as $language_id => $value) {
            $this->db->query("UPDATE " . DB_PREFIX . "product_description SET name = '" . $this->db->escape($value['name']) . "', description = '" . $this->db->escape($value['description']) . "', meta_title = '" . $this->db->escape($value['meta_title']) . "', meta_description = '" . $this->db->escape($value['meta_description']) . "', meta_keyword = '" . $this->db->escape($value['meta_keyword']) . "' WHERE product_id = '" . (int)$product_id . "' AND language_id = '" . (int)$language_id . "'");
        }

        // Update attributes
        if (isset($data['attributes']) && !empty($data['attributes'])) {
            $attributes = json_decode($data['attributes'], true);
            if (json_last_error() === JSON_ERROR_NONE && is_array($attributes)) {
                foreach ($attributes as $attribute) {
                    if (isset($attribute['attribute_id']) && isset($attribute['text']) && isset($attribute['language_id'])) {
                        $attribute_id = (int)$attribute['attribute_id'];
                        $text = $attribute['text'];
                        $language_id = (int)$attribute['language_id'];
                        
                        if ($attribute_id > 0) {
                            // Check if attribute exists
                            $existing_attribute = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_attribute WHERE product_id = '" . (int)$product_id . "' AND attribute_id = '" . (int)$attribute_id . "' AND language_id = '" . (int)$language_id . "'");
                            
                            if ($existing_attribute->num_rows) {
                                // Update existing attribute
                                $this->db->query("UPDATE " . DB_PREFIX . "product_attribute SET text = '" . $this->db->escape($text) . "' WHERE product_id = '" . (int)$product_id . "' AND attribute_id = '" . (int)$attribute_id . "' AND language_id = '" . (int)$language_id . "'");
                            } else {
                                // Insert new attribute
                                $this->db->query("INSERT INTO " . DB_PREFIX . "product_attribute SET product_id = '" . (int)$product_id . "', attribute_id = '" . (int)$attribute_id . "', language_id = '" . (int)$language_id . "', text = '" . $this->db->escape($text) . "'");
                            }
                        }
                    }
                }
            }
        }

        // Update options
        if (isset($data['options']) && !empty($data['options'])) {
            $options = json_decode($data['options'], true);
            if (json_last_error() === JSON_ERROR_NONE && is_array($options)) {
                // 先删除现有的product_option和product_option_value
                $this->db->query("DELETE pov FROM " . DB_PREFIX . "product_option_value pov 
                    LEFT JOIN " . DB_PREFIX . "product_option po ON (pov.product_option_id = po.product_option_id) 
                    WHERE po.product_id = '" . (int)$product_id . "'");
                $this->db->query("DELETE FROM " . DB_PREFIX . "product_option WHERE product_id = '" . (int)$product_id . "'");
                
                foreach ($options as $option) {
                    if (isset($option['option_id']) && isset($option['type']) && isset($option['values']) && is_array($option['values'])) {
                        // 添加product_option
                        $this->db->query("INSERT INTO " . DB_PREFIX . "product_option SET 
                            product_id = '" . (int)$product_id . "',
                            option_id = '" . (int)$option['option_id'] . "',
                            required = '1'");
                        $product_option_id = $this->db->getLastId();
                        
                        // 添加option values
                        foreach ($option['values'] as $value) {
                            if (isset($value['option_value_id'])) {
                                $this->db->query("INSERT INTO " . DB_PREFIX . "product_option_value SET 
                                    product_option_id = '" . (int)$product_option_id . "',
                                    product_id = '" . (int)$product_id . "',
                                    option_id = '" . (int)$option['option_id'] . "',
                                    option_value_id = '" . (int)$value['option_value_id'] . "',
                                    quantity = '1000',
                                    subtract = '0',
                                    price = '0',
                                    price_prefix = '+'");
                            }
                        }
                    }
                }
            }
        }
    }

    private function cleanImageUrls($content) {
        if (empty($content)) {
            return $content;
        }

        // 使用回调函数处理每个img标签
        return preg_replace_callback('/<img[^>]*src=["\'](.*?)["\'][^>]*>/i', function($matches) {
            $url = $matches[1];
            
            // 处理URL中的空格和中文感叹号
            $url = str_replace(' ', '', $url);  // 替换空格
            $url = str_replace('！', '!', $url);   // 替换中文感叹号为英文感叹号
            
            // 重建img标签，保持其他属性不变
            $full_tag = str_replace($matches[1], $url, $matches[0]);
            
            return $full_tag;
        }, $content);
    }

    public function import(): void {
        $this->load->language('catalog/product_import_export');
        
        $json = [];

        if (!$this->user->hasPermission('modify', 'catalog/product')) {
            $json['error'] = $this->language->get('error_permission');
        }

        if (empty($json['error'])) {
            if (!isset($this->request->files['file']['tmp_name']) || !is_uploaded_file($this->request->files['file']['tmp_name'])) {
                if (isset($this->request->files['file']['error'])) {
                    switch ($this->request->files['file']['error']) {
                        case UPLOAD_ERR_INI_SIZE:
                            $max_size = ini_get('upload_max_filesize');
                            $json['error'] = sprintf($this->language->get('error_upload_ini_size'), $max_size);
                            break;
                        case UPLOAD_ERR_FORM_SIZE:
                            $json['error'] = $this->language->get('error_upload_form_size');
                            break;
                        case UPLOAD_ERR_PARTIAL:
                            $json['error'] = $this->language->get('error_upload_partial');
                            break;
                        case UPLOAD_ERR_NO_FILE:
                            $json['error'] = $this->language->get('error_upload_no_file');
                            break;
                        case UPLOAD_ERR_NO_TMP_DIR:
                            $json['error'] = $this->language->get('error_upload_no_temp');
                            break;
                        case UPLOAD_ERR_CANT_WRITE:
                            $json['error'] = $this->language->get('error_upload_write');
                            break;
                        case UPLOAD_ERR_EXTENSION:
                            $json['error'] = $this->language->get('error_upload_stopped');
                            break;
                        default:
                            $json['error'] = sprintf($this->language->get('error_upload_unknown'), $this->request->files['file']['error']);
                            break;
                    }
                } else {
                    $json['error'] = $this->language->get('error_upload');
                }
            }
        }

        if (empty($json['error'])) {
            $csv_file = $this->request->files['file']['tmp_name'];
            // 检查CSV文件行数
            $row_count = 0;
            $handle = fopen($csv_file, 'r');
            if ($handle !== false) {
                while (fgets($handle) !== false) {
                    $row_count++;
                    if ($row_count > 500) {
                        fclose($handle);
                        $json['error'] = $this->language->get('upload_max_row');
                        break;
                    }
                }
            }
            if (empty($json['error']) && !empty($csv_file) && is_uploaded_file($csv_file)) {
                // 检测文件编码并转换为UTF-8
                $content = file_get_contents($csv_file);
                if ($content === false) {
                    $json['error'] = '无法读取上传的文件';
                } else {
                    $bom = pack("CCC", 0xef, 0xbb, 0xbf);
                    if (0 === strncmp($content, $bom, 3)) {
                        $content = substr($content, 3);
                    }
                    
                    // 将内容写入临时文件
                    $temp_file = tempnam(sys_get_temp_dir(), 'csv');
                    file_put_contents($temp_file, $content);
                    
                    $handle = fopen($temp_file, 'r');
                    
                    // Get header row and trim whitespace
                    $header = array_map('trim', fgetcsv($handle));
                    
                    // Required fields
                    $required_fields = ['product_id', 'name'];
                    
                    // Check required fields
                    $missing_fields = [];
                    foreach ($required_fields as $field) {
                        if (!in_array($field, $header)) {
                            $missing_fields[] = $field;
                        }
                    }
                    
                    if (!empty($missing_fields)) {
                        $json['error'] = sprintf($this->language->get('error_required_field'), implode(', ', $missing_fields));
                        fclose($handle);
                        unlink($temp_file);
                    } else {
                        $success_count = 0;
                        $error_count = 0;
                        
                        // Create header index map
                        $header_map = array_flip($header);
                        
                        // Process products
                        while (($row = fgetcsv($handle)) !== FALSE) {
                            // Map CSV data to header
                            $product_data = [];
                            foreach ($header as $index => $field) {
                                if (isset($row[$index])) {
                                    $product_data[$field] = trim($row[$index]);
                                }
                            }
                            
                            // 检查product_id是否存在且有效
                            $product_id = isset($product_data['product_id']) ? (int)$product_data['product_id'] : 0;
                            if ($product_id <= 0) {
                                $error_count++;
                                $this->log->write('Import error: Invalid product ID in row');
                                continue;
                            }

                            // 检查产品是否存在
                            $product_exists = $this->db->query("SELECT COUNT(*) as total FROM " . DB_PREFIX . "product WHERE product_id = '" . (int)$product_id . "'");
                            if ($product_exists->row['total'] == 0) {
                                $error_count++;
                                $this->log->write('Import error: Product ID ' . $product_id . ' does not exist');
                                continue;
                            }

                            try {
                                // 准备产品描述数据
                                $product_description = [];
                                
                                // 合并描述并清理URL
                                $merged_description = implode("\n", [
                                    $product_data['description_1'] ?? '',
                                    $product_data['description_2'] ?? '',
                                    $product_data['description_3'] ?? ''
                                ]);
                                
                                // 清理描述中的图片URL
                                $cleaned_description = $this->cleanImageUrls($merged_description);
                                
                                $product_description[1] = [  // 假设语言ID为1
                                    'name' => $product_data['name'] ?? '',
                                    'description' => $cleaned_description,
                                    'meta_title' => $product_data['meta_title'] ?? '',
                                    'meta_description' => $product_data['meta_description'] ?? '',
                                    'meta_keyword' => $product_data['meta_keyword'] ?? '',
                                ];
                                
                                $product_data['product_description'] = $product_description;
                                
                                // 处理attributes数据
                                if (isset($product_data['attributes']) && !empty($product_data['attributes'])) {
                                    // $this->log->write('==================== 开始处理属性 ====================');
                                    // $this->log->write('产品ID: ' . $product_id);
                                    // $this->log->write('原始属性数据: ' . print_r($product_data['attributes'], true));
                                    
                                    // 清理和标准化JSON字符串
                                    $attributes_json = $product_data['attributes'];
                                    $attributes_json = str_replace(['Attribute_id', 'Text'], ['attribute_id', 'text'], $attributes_json);
                                    $attributes_json = preg_replace('/\s+/', ' ', $attributes_json); // 删除多余的空格
                                    $attributes_json = preg_replace('/([{,])\s*"(\w+)"\s*:/', '$1"$2":', $attributes_json); // 标准化键名格式
                                    
                                    // $this->log->write('清理后的JSON数据: ' . $attributes_json);
                                    
                                    $attributes = json_decode($attributes_json, true);
                                    if (json_last_error() !== JSON_ERROR_NONE) {
                                        $this->log->write('JSON解析错误: ' . json_last_error_msg());
                                        $this->log->write('JSON解析错误代码: ' . json_last_error());
                                    } elseif (!is_array($attributes)) {
                                        $this->log->write('解析后的数据不是数组');
                                    } else {
                                        // $this->log->write('成功解析属性数据: ' . print_r($attributes, true));
                                        
                                        try {
                                            // 先删除现有的属性
                                            $delete_sql = "DELETE FROM " . DB_PREFIX . "product_attribute WHERE product_id = '" . (int)$product_id . "'";
                                            $this->db->query($delete_sql);
                                            $this->log->write('执行删除SQL: ' . $delete_sql);
                                            
                                            foreach ($attributes as $index => $attribute) {
                                                $this->log->write('处理第' . ($index + 1) . '个属性: ' . print_r($attribute, true));
                                                
                                                // 标准化键名
                                                $attribute = array_change_key_case($attribute, CASE_LOWER);
                                                $this->log->write('标准化后的属性数据: ' . print_r($attribute, true));
                                                
                                                if (!isset($attribute['attribute_id'])) {
                                                    $this->log->write('缺少attribute_id字段');
                                                    continue;
                                                }
                                                if (!isset($attribute['text'])) {
                                                    $this->log->write('缺少text字段');
                                                    continue;
                                                }

                                                $attribute_id = (int)$attribute['attribute_id'];
                                                $text = $attribute['text'];
                                                $language_id = isset($attribute['language_id']) ? (int)$attribute['language_id'] : (int)$this->config->get('config_language_id');
                                                
                                                $this->log->write('处理属性: ID=' . $attribute_id . ', 文本=' . $text . ', 语言ID=' . $language_id);
                                                
                                                // 验证attribute_id是否存在
                                                $check_sql = "SELECT attribute_id FROM " . DB_PREFIX . "attribute WHERE attribute_id = '" . (int)$attribute_id . "'";
                                                $attribute_exists = $this->db->query($check_sql);
                                                $this->log->write('检查属性SQL: ' . $check_sql);
                                                $this->log->write('属性存在检查结果: ' . $attribute_exists->num_rows . ' 行');
                                                
                                                if ($attribute_exists->num_rows == 0) {
                                                    $this->log->write('属性ID不存在: ' . $attribute_id);
                                                    continue;
                                                }

                                                try {
                                                    // 更新attribute_description的name
                                                    if (isset($attribute['name'])) {
                                                        $update_name_sql = "UPDATE " . DB_PREFIX . "attribute_description 
                                                            SET name = '" . $this->db->escape($attribute['name']) . "'
                                                            WHERE attribute_id = '" . (int)$attribute_id . "'
                                                            AND language_id = '" . (int)$language_id . "'";
                                                        $this->db->query($update_name_sql);
                                                        // $this->log->write('执行更新属性名称SQL: ' . $update_name_sql);
                                                    }
                                                    
                                                    // 添加产品属性
                                                    $insert_sql = "INSERT INTO " . DB_PREFIX . "product_attribute SET 
                                                        product_id = '" . (int)$product_id . "',
                                                        attribute_id = '" . (int)$attribute_id . "',
                                                        language_id = '" . (int)$language_id . "',
                                                        text = '" . $this->db->escape($text) . "'";
                                                    $this->db->query($insert_sql);
                                                    // $this->log->write('执行插入属性SQL: ' . $insert_sql);
                                                    
                                                    // 检查插入是否成功
                                                    $check_insert_sql = "SELECT * FROM " . DB_PREFIX . "product_attribute 
                                                        WHERE product_id = '" . (int)$product_id . "' 
                                                        AND attribute_id = '" . (int)$attribute_id . "' 
                                                        AND language_id = '" . (int)$language_id . "'";
                                                    $check_result = $this->db->query($check_insert_sql);
                                                    $this->log->write('检查插入结果: ' . ($check_result->num_rows > 0 ? '成功' : '失败'));
                                                    
                                                } catch (Exception $e) {
                                                    $this->log->write('数据库操作错误: ' . $e->getMessage());
                                                    $this->log->write('错误追踪: ' . $e->getTraceAsString());
                                                }
                                            }
                                        } catch (Exception $e) {
                                            $this->log->write('处理属性时发生错误: ' . $e->getMessage());
                                            $this->log->write('错误追踪: ' . $e->getTraceAsString());
                                        }
                                    }
                                    // $this->log->write('==================== 属性处理结束 ====================');
                                } else {
                                    $this->log->write('没有找到属性数据，产品ID: ' . $product_id);
                                }
                                // 处理options数据
                                if (isset($product_data['options']) && !empty($product_data['options'])) {
                                    $options = json_decode($product_data['options'], true);
                                    if (json_last_error() === JSON_ERROR_NONE && is_array($options)) {
                                        foreach ($options as $option) {
                                            if (isset($option['option_id']) && isset($option['values']) && is_array($option['values'])) {
                                                // 创建product_option
                                                $this->db->query("INSERT INTO " . DB_PREFIX . "product_option SET 
                                                    product_id = '" . (int)$product_id . "',
                                                    option_id = '" . (int)$option['option_id'] . "',
                                                    required = '1'");
                                                
                                                $product_option_id = $this->db->getLastId();
                                                
                                                // 添加所有option values
                                                foreach ($option['values'] as $value) {
                                                    if (isset($value['option_value_id'])) {
                                                        $this->db->query("INSERT INTO " . DB_PREFIX . "product_option_value SET 
                                                            product_option_id = '" . (int)$product_option_id . "',
                                                            product_id = '" . (int)$product_id . "',
                                                            option_id = '" . (int)$option['option_id'] . "',
                                                            option_value_id = '" . (int)$value['option_value_id'] . "',
                                                            quantity = '1000',
                                                            subtract = '0',
                                                            price = '0',
                                                            price_prefix = '+'");
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                                // 更新option_value_description表的name字段
                                if (isset($product_data['options']) && !empty($product_data['options'])) {
                                    $options = json_decode($product_data['options'], true);
                                    if (json_last_error() === JSON_ERROR_NONE && is_array($options)) {
                                        foreach ($options as $option) {
                                            if (isset($option['option_id']) && isset($option['values']) && is_array($option['values'])) {
                                                foreach ($option['values'] as $value) {
                                                    if (isset($value['option_value_id']) && isset($value['name'])) {
                                                        // 更新option_value的名称
                                                        $this->db->query("UPDATE " . DB_PREFIX . "option_value_description 
                                                            SET name = '" . $this->db->escape($value['name']) . "'
                                                            WHERE option_value_id = '" . (int)$value['option_value_id'] . "'
                                                            AND language_id = '" . (int)$this->config->get('config_language_id') . "'");
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                                // 更新产品
                                $this->editProduct($product_id, $product_data);
                                $success_count++;
                            } catch (Exception $e) {
                                $error_count++;
                                $this->log->write('Import error for product ' . $product_id . ': ' . $e->getMessage());
                            }
                        }
                        
                        $json['success'] = sprintf($this->language->get('text_success_import'), $success_count, $error_count);
                        
                        fclose($handle);
                        unlink($temp_file);
                    }
                }
            }
        }

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }
}
